/**
 * <p>Title: UserSecurityInterceptor.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2015</p>
 * <p>Company: SiySoft</p>
 * @author liguanghui
 * @date 2015年5月25日
 * @version 1.0
 */
package com.siysoft.tc.base.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserSecurityInterceptor implements HandlerInterceptor {
	private List<String> excludedUrls;
	private String defaultTargetUrl;

	public void setExcludedUrls(List<String> excludedUrls) {
		this.excludedUrls = excludedUrls;
	}

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
			throws Exception {
		String requestUri = request.getRequestURI();
		for (String url : this.excludedUrls) {
			if (requestUri.endsWith(url)) {
				return true;
			}
		}
		if (SecurityContextHolder.getContext().getAuthentication() == null) {
			response.sendRedirect(request.getContextPath()
					+ this.defaultTargetUrl);
			return false;
		}
		return true;
	}

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	public String getDefaultTargetUrl() {
		return this.defaultTargetUrl;
	}

	public void setDefaultTargetUrl(String defaultTargetUrl) {
		this.defaultTargetUrl = defaultTargetUrl;
	}
}
